<?php

class Curl {
	//cURL句柄
	protected $_handle = null;
	
	//构造函数
	public function __construct($host=null){
		if (!function_exists('curl_init')) {
			E::halt('服务器还没有开启curl功能支持');
		}
		
		if ($this->_handle === null){
			$this->_handle = curl_init($host);
		}
	}
	
	//关闭cURL连接
	private function close(){
		return $this->_handle && curl_close($this->_handle);
	}
	
	//获取错误信息
	public function error(){
		return curl_error($this->_handle);
	}
	
	//执行并返回结果
	public function exec(){
		ob_start();
		curl_exec($this->_handle);
		return ob_get_clean();
	}
	
	//GET请求获取数据
	public function get(){
		return $this->setopt(CURLOPT_POST, false)
			 ->exec();
	}
	
	//设置CURLOPT_URL选项（ 需要获取的URL地址）
	public function host($url){
		$this->setopt(CURLOPT_URL, $url);
		return $this;
	}
	
	/**
	 * 
	 * +------------------------------------------------------------+
	 * @name post
	 * +------------------------------------------------------------+
	 * POST提交数据，并返回执行结果
	 * +------------------------------------------------------------+
	 *
	 * 参数的格式如：p1=v1&p2=v2 或 arra('p1' => 'v1', 'p2' => 'v2')
	 *
	 * @param mixed $datas
	 *
	 */
	public function post($datas){
		$options = array(
			CURLOPT_POST => true,
			CURLOPT_POSTFIELDS => $datas
		);
		
		return $this->setopts($options)
			        ->exec();
	}
	
	/**
	 * 
	 * +------------------------------------------------------------+
	 * @name referer
	 * +------------------------------------------------------------+
	 * 设置在HTTP请求头中"Referer: "的内容
	 * +------------------------------------------------------------+
	 *
	 * @param string $url
	 *
	 */
	public function referer($url){
		$this->setopt(CURLOPT_REFERER, $url);
		
		return $this;
	}
	
	/**
	 * 
	 * +------------------------------------------------------------+
	 * @name setopt
	 * +------------------------------------------------------------+
	 * 设置CURL传输选项
	 * +------------------------------------------------------------+
	 *
	 * @param string $option 选项
	 * @param mixed $value	   值
	 *
	 */
	public function setopt($option,$value){
		curl_setopt($this->_handle,$option,$value);
		return $this;
	}
	
	/**
	 * 
	 * +------------------------------------------------------------+
	 * @name setopts
	 * +------------------------------------------------------------+
	 * 为cURL传输会话批量设置选项
	 * +------------------------------------------------------------+
	 *
	 * 参数格式如： array(CURLOPT_URL => $url)
	 *
	 * @param array $options
	 *
	 */
	public function setopts($options){
		if (function_exists('curl_setopt_array')){
			curl_setopt_array($this->_handle, $options);
		}else{
			foreach ($options as $key=>$opt){
				$this->setopt($key, $opt);
			}
		}
		
		return $this;
	}
	
	public function __destruct(){
		$this->close();
	}
}

?>